import subprocess
import os
from pathlib import Path
import signal
import time
import logging
import tempfile

logging.basicConfig(level=logging.WARNING)  # 修改为WARNING级别
logger = logging.getLogger(__name__)


def convert_to_pdf(input_path, output_folder):
    try:
        logger.info(f"开始转换文件: {os.path.basename(input_path)}")
        # 创建临时文件夹
        temp_dir = tempfile.mkdtemp()
        logger.info(f"创建临时文件夹: {temp_dir}")

        filename = os.path.basename(input_path)
        name, ext = os.path.splitext(filename)
        temp_output_path = os.path.join(temp_dir, f"{name}.pdf")

        cmd = ['libreoffice', '--headless', '--convert-to', 'pdf', input_path, '--outdir', temp_dir]
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True)

        # 实时输出日志
        while proc.poll() is None:
            stdout_line = proc.stdout.readline()
            if stdout_line:
                logger.info(f"转换进度: {stdout_line.decode().strip()}")
            time.sleep(0.5)

        if proc.returncode != 0:
            error_msg = proc.stderr.read().decode()
            logger.error(f"转换失败: {error_msg}")
            raise Exception(f"转换失败: {error_msg}")

        # 确保输出文件夹存在
        Path(output_folder).mkdir(parents=True, exist_ok=True)
        final_output_path = os.path.join(output_folder, f"{name}.pdf")
        # 将临时文件移动到最终输出文件夹
        os.rename(temp_output_path, final_output_path)
        logger.info(f"文件转换完成: {final_output_path}")

        # 删除临时文件夹
        os.rmdir(temp_dir)
        logger.info(f"删除临时文件夹: {temp_dir}")

        return final_output_path
    except Exception as e:
        logger.error(f"转换异常: {str(e)}")
        try:
            os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
        except:
            pass
        raise Exception(f"文件转换失败: {str(e)}")
